//
//  HOTCreateFreeInfoViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-10-9.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTCreateFreeSceneViewController.h"
#import "ZZZUIScrollView+Extends.h"
#import "ZZZDatePicker.h"
#import "UITextField+extend.h"
#import "HOTPopupView.h"

@interface HOTCreateFreeSceneViewController ()<UITextFieldDelegate,UITextViewDelegate>

@property(nonatomic,copy)NSString *startDate;
@property(nonatomic,copy)NSString *endDate;
@end

@implementation HOTCreateFreeSceneViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"現場情報"];
    
    [self initView];
}

-(void)initView {
    
    [self addRightBtnTarget:self action:@selector(contruibuteBtnClicked) image:[UIImage imageNamed:@"btn_contribute_off"] hImage:[UIImage imageNamed:@"btn_contribute_on"]];
    
    _contentBgImageView.image = [_contentBgImageView.image stretchableImageWithLeftCapWidth:30 topCapHeight:18];
    _contentTextView.inputAccessoryView = [HOTUtils createInputAccessoryViewWithName:MSG_INPUT_BAR_DONE target:self action:@selector(keyBoardDoneBtnClicked:)];
    
    _jobTypePullDownView.parentView = _mainScrollView;
    _personNumPullDownView.parentView = _mainScrollView;
    _regionPullDownView.parentView = _mainScrollView;
    _cityPullDownView.parentView = _mainScrollView;
    
    _contentTextView.font = ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 16);
    _startDateText.font= ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 16);
    _endDateText.font= ZZZ_fontWithName(kHOT_FONT_ROUNDED_X, 16);
    
    _jobTypePullDownView.pullDownModelList = [HOTUtils getJobPullModelListFromPlist];
    _personNumPullDownView.pullDownModelList = [self createPersonNumModelList];
    
    //__block UIScrollView *blocScrollView = _mainScrollView;
     __unsafe_unretained HOTCreateFreeSceneViewController *blockObj = self;
    _jobTypePullDownView.WhenBtnClicked = ^ (void) {
        
        [blockObj hiddenKeyBoard];
        [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
    };
    
    __unsafe_unretained HOTCommTextField *tempTextField = _otherJobNameText;
    __unsafe_unretained UIScrollView *tempScrollView = _mainScrollView;
    _jobTypePullDownView.SelectedComplete = ^(ZZZPullDownModel *model) {
        
        int constantValue = 0;
        if ([model.titleStr isEqualToString:@"その他"]) {
            
            constantValue = 41;
        }
        
        NSArray *constraints = tempTextField.constraints;
        
        for (NSLayoutConstraint *constraint in constraints) {
            
            if (constraint.firstItem == tempTextField
                && constraint.firstAttribute == NSLayoutAttributeHeight) {
                
                
                constraint.constant = constantValue;
                [tempTextField layoutIfNeeded];
                [UIView animateWithDuration:0.3 animations:^{
                    [tempScrollView layoutIfNeeded];
                    
                }];
                break;
            }
        }
        
    };
    
    _personNumPullDownView.WhenBtnClicked = ^ (void) {
        
        [blockObj hiddenKeyBoard];
        [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
    };
    
    __block UITextField *blockStartDateTextText = _startDateText;
    ZZZDatePicker *_datePicker = [ZZZDatePicker createWithTextField:_startDateText
                                 doneCompletionBlock:^(NSDate *selDate) {
                                     
                                     [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
                                     NSString *dateStr = [ZZZUtils formartDate:selDate withStyle:@"yyyy年MM月dd日"];
                                     blockObj.startDate = [ZZZUtils formartDate:selDate withStyle:@"yyyy-MM-dd"];
                                     blockStartDateTextText.text = [HOTUtils getString:dateStr];
                                     
                                 }
                               cancelCompletionBlock:^{
                                   
                                   [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
                               }];
    [_datePicker setDatePickerMode:UIDatePickerModeDate];
    
    __block UITextField *blockEndDateTextText = _endDateText;
    _datePicker = [ZZZDatePicker createWithTextField:blockEndDateTextText
                                                doneCompletionBlock:^(NSDate *selDate) {
                                                    
                                                    [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
                                                    NSString *dateStr = [ZZZUtils formartDate:selDate withStyle:@"yyyy年MM月dd日"];
                                                    blockObj.endDate =  [ZZZUtils formartDate:selDate withStyle:@"yyyy-MM-dd"];
                                                    blockEndDateTextText.text = [HOTUtils getString:dateStr];
                                                    
                                                }
                                              cancelCompletionBlock:^{
                                                  
                                                  [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
                                              }];
    [_datePicker setDatePickerMode:UIDatePickerModeDate];
    
    _regionPullDownView.pullDownModelList = [HOTUtils getRegionModelList];
    
   
    
    _regionPullDownView.WhenBtnClicked = ^ (void) {
        
        [blockObj hiddenKeyBoard];
        [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
    };
    
    _regionPullDownView.SelectedComplete = ^(ZZZPullDownModel *model) {
        
        NSArray *subCitys = [model.userInfo objectForKey:@"list"];
        _cityPullDownView.pullDownModelList = subCitys;
        _cityPullDownView.selectedModel = [subCitys firstObject];
    };
    
    _cityPullDownView.WhenBtnClicked = ^ (void) {
        
        [blockObj hiddenKeyBoard];
        [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
    };
}

-(void)requestUpdate {
    
    
    [self showLoading];
    
    NSString *jobId = _jobTypePullDownView.selectedModel.value;
    NSString *jobName = _jobTypePullDownView.selectedModel.titleStr;
    if ([jobName isEqualToString:@"その他"]) {
        jobId = @"0";
        jobName = [HOTUtils getString:_otherJobNameText.text];
    }
    
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_USER_JOB_ID:jobId,
                                 REQ_KEY_USER_JOB_NAME:jobName,
                                 REQ_KEY_WORKER_SUM:_personNumPullDownView.selectedModel.value,
                                 REQ_KEY_START_TIME:self.startDate,
                                 REQ_KEY_END_TIME:self.endDate,
                                 REQ_KEY_CITY_ID:_regionPullDownView.selectedModel.value,
                                 REQ_KEY_DISTRICT:_cityPullDownView.selectedModel.titleStr,
                                 REQ_KEY_WORKP_DETAIL:_contentTextView.text};
    
    __unsafe_unretained HOTCreateFreeSceneViewController *tempObj = self;
    [self requestWithURL:HOT_URL_SCENE_PUSH Parameters:parameters success:^(NSInteger result, NSDictionary * data) {
        
        
        [tempObj showSuccessWithMessage:MSG_SUCCESS complection:^{
            
            [tempObj.navigationController popViewControllerAnimated:YES];
        }];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}


-(NSArray *)createPersonNumModelList {
    
    NSMutableArray *modelList = [NSMutableArray array];
    for (int i =1; i < 11; i ++) {
        
        if (i == 10) {
            
            ZZZPullDownModel *model = [[ZZZPullDownModel alloc] init];
            model.titleStr = [NSString stringWithFormat:@"%d人以上", i];
            model.value = [NSString stringWithFormat:@"%d",i];
            [modelList addObject:model];
            break;
        }
        
        ZZZPullDownModel *model = [[ZZZPullDownModel alloc] init];
        model.titleStr = [NSString stringWithFormat:@"%d人", i];
        model.value = [NSString stringWithFormat:@"%d",i];
        [modelList addObject:model];
    }
    
    return modelList;
}

-(void)keyBoardDoneBtnClicked:(UIButton *)doneBtn {
    
    [_contentTextView resignFirstResponder];
    
    [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

-(void)contruibuteBtnClicked {
    
    [self hiddenKeyBoard];
    
    if (![self checkParametersValid]) {
        
        return;
    }
    
    [self requestUpdate];
//
//    HOTPopupView *popupView = [[HOTPopupView alloc] initWithTitle:@"確認" message:@"详细を見るには600現使用します。\n よろしいですか？"];
//    
//    __unsafe_unretained HOTCreateFreeInfoViewController *unretainObj = self;
//    popupView.popBtnClickedBlock = ^(HOTPopBtnType btnType) {
//        
//        if (btnType == HOTPopOKBtn) {
//            
//            [self.hudManager showMessage:MSG_SUCCESS duration:1.5 complection:^{
//                [unretainObj.navigationController popViewControllerAnimated:YES];
//            }];
//        }
//    };
//    [popupView showInWindow];
    
    
}

-(void)hiddenKeyBoard {
    
    [_startDateText resignFirstResponder];
    [_endDateText resignFirstResponder];
    [_contentTextView resignFirstResponder];
    
    [_mainScrollView setContentOffset:CGPointMake(0, 0)];
}

-(BOOL)checkParametersValid {
    
    NSString *errName = @"";
    HOTInputItemType inputType = 0;
    if (_jobTypePullDownView.selectedModel == nil) {
        
        errName = @"職種";
        inputType = HOTInputItemPullDown;
    } else if ([_jobTypePullDownView.selectedModel.titleStr isEqualToString:@"その他"]
               && [_otherJobNameText textIsNullOrEmpty]) {
        
        errName = @"職種";
        inputType = HOTInputItemText;
    } else if (_personNumPullDownView.selectedModel == nil) {
        
        errName = @"人数";
        inputType = HOTInputItemPullDown;
        
    } else if ([_startDateText textIsNullOrEmpty] || [_endDateText textIsNullOrEmpty]) {
        
        errName = @"日程";
        inputType = HOTInputItemPullDown;
        
    } else if (_regionPullDownView.selectedModel == nil || _cityPullDownView.selectedModel == nil) {
        
        errName = @"対応可能地域";
        inputType = HOTInputItemPullDown;
        
    } else if (!_contentTextView.text || [_contentTextView.text isEqualToString:@""]) {
        
        errName = @"詳细内容等";
        inputType = HOTInputItemText;
    }

    if (errName.length > 0) {
        
        NSString * errMsg = [self getErrMsgWith:errName itemType:inputType];
        
        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:errMsg delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
        
        [popupView showInWindow];
        
        return NO;
    }
    
    NSDate *startDate = [ZZZUtils formartStr:_startDateText.text withStyle:@"yyyy年MM月dd日"];
    NSDate *endDate = [ZZZUtils formartStr:_endDateText.text withStyle:@"yyyy年MM月dd日"];
    
    if ([startDate timeIntervalSince1970] >= [endDate timeIntervalSince1970]) {
        
        ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE message:MSG_WRONG_DATE delegate:nil cancelButtonTitle:nil otherButtonTitle:ALERT_BTN_OK];
        
        [popupView showInWindow];
        
        return NO;
    }
    
    
    return YES;
}

#pragma delegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    [_mainScrollView scrollViewToVisible:textField animated:YES];
    
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    [_mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    
    return YES;
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    
    [_mainScrollView scrollViewToVisible:textView animated:YES];
    
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
